import { ref, computed } from 'vue'

export interface WalletState {
  isConnected: boolean
  address: string
  balance: string
  usdtBalance: string
}

export interface Transaction {
  hash: string
  from: string
  to: string
  amount: string
  timestamp: number
  status: 'pending' | 'success' | 'failed'
}

// USDT TRC20 contract address
const USDT_CONTRACT_ADDRESS = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'

export function useTronWallet() {
  const walletState = ref<WalletState>({
    isConnected: false,
    address: '',
    balance: '0',
    usdtBalance: '0'
  })

  const isLoading = ref(false)
  const error = ref('')
  const transactions = ref<Transaction[]>([])

  const tronWeb = computed(() => {
    return (window as any).tronWeb
  })

  const isTronLinkInstalled = computed(() => {
    return !!(window as any).tronLink
  })

  const connectWallet = async () => {
    try {
      isLoading.value = true
      error.value = ''

      if (!isTronLinkInstalled.value) {
        throw new Error('请安装 TronLink 钱包扩展')
      }

      // Request account access
      const result = await (window as any).tronLink.request({
        method: 'tron_requestAccounts'
      })

      if (result.code === 200) {
        walletState.value.isConnected = true
        walletState.value.address = tronWeb.value.defaultAddress.base58
        await updateBalances()
      } else {
        throw new Error('钱包连接失败')
      }
    } catch (err: any) {
      error.value = err.message || '连接钱包时发生错误'
      console.error('Connect wallet error:', err)
    } finally {
      isLoading.value = false
    }
  }

  const disconnectWallet = () => {
    walletState.value = {
      isConnected: false,
      address: '',
      balance: '0',
      usdtBalance: '0'
    }
    transactions.value = []
  }

  const updateBalances = async () => {
    if (!walletState.value.isConnected) return

    try {
      // Get TRX balance
      const trxBalance = await tronWeb.value.trx.getBalance(walletState.value.address)
      walletState.value.balance = tronWeb.value.fromSun(trxBalance)

      // Get USDT balance
      const contract = await tronWeb.value.contract().at(USDT_CONTRACT_ADDRESS)
      const usdtBalance = await contract.balanceOf(walletState.value.address).call()
      walletState.value.usdtBalance = tronWeb.value.toBigNumber(usdtBalance).dividedBy(1000000).toFixed(2)
    } catch (err) {
      console.error('Update balances error:', err)
    }
  }

  const sendUSDT = async (toAddress: string, amount: string) => {
    if (!walletState.value.isConnected) {
      throw new Error('钱包未连接')
    }

    try {
      isLoading.value = true
      error.value = ''

      // Validate address
      if (!tronWeb.value.isAddress(toAddress)) {
        throw new Error('接收地址格式无效')
      }

      // Validate amount
      const sendAmount = parseFloat(amount)
      const currentBalance = parseFloat(walletState.value.usdtBalance)
      
      if (sendAmount <= 0) {
        throw new Error('转账金额必须大于0')
      }
      
      if (sendAmount > currentBalance) {
        throw new Error('USDT余额不足')
      }

      // Get contract
      const contract = await tronWeb.value.contract().at(USDT_CONTRACT_ADDRESS)
      
      // Convert amount to contract units (6 decimals for USDT)
      const amountInUnits = tronWeb.value.toBigNumber(sendAmount).multipliedBy(1000000)

      // Send transaction
      const result = await contract.transfer(toAddress, amountInUnits).send({
        feeLimit: 100000000, // 100 TRX fee limit
        callValue: 0,
        shouldPollResponse: true
      })

      // Add transaction to history
      const transaction: Transaction = {
        hash: result,
        from: walletState.value.address,
        to: toAddress,
        amount: amount,
        timestamp: Date.now(),
        status: 'pending'
      }

      transactions.value.unshift(transaction)

      // Update balances
      await updateBalances()

      return result
    } catch (err: any) {
      error.value = err.message || '转账失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const getTransactionStatus = async (txHash: string) => {
    try {
      const result = await tronWeb.value.trx.getTransactionInfo(txHash)
      return result.receipt?.result === 'SUCCESS' ? 'success' : 'failed'
    } catch (err) {
      return 'pending'
    }
  }

  const formatAddress = (address: string) => {
    if (!address) return ''
    return `${address.slice(0, 6)}...${address.slice(-4)}`
  }

  const formatAmount = (amount: string | number) => {
    const num = typeof amount === 'string' ? parseFloat(amount) : amount
    return num.toLocaleString('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 6
    })
  }

  return {
    walletState,
    isLoading,
    error,
    transactions,
    isTronLinkInstalled,
    connectWallet,
    disconnectWallet,
    updateBalances,
    sendUSDT,
    getTransactionStatus,
    formatAddress,
    formatAmount
  }
}